// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod file_io;
mod ctp_commands;
mod logger;
mod system_monitor;
mod audio_manager;
mod audio_commands;

#[tokio::main]
async fn main() {
    // 设置全局panic处理器
    setup_panic_handler();
    
    // 初始化日志系统
    if let Err(e) = logger::init_logger() {
        eprintln!("Failed to initialize logger: {}", e);
        return;
    }
    
    // 记录应用启动
    logger::log_app_start();
    logger::log_memory_usage();
    
    // 设置优雅关闭处理
    setup_shutdown_handler();
    
    // 启动系统监控器（每5分钟记录一次系统状态）
    let monitor = system_monitor::SystemMonitor::new(5);
    monitor.start();

    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            file_io::read_file,
            file_io::write_file,
            file_io::ensure_directory,
            file_io::path_exists,
            file_io::save_config_file,
            file_io::read_config_file,
            file_io::write_cache_file,
            file_io::read_cache_file,
            file_io::clear_cache_file,
            file_io::get_cache_info,
            ctp_commands::get_api_version,
            ctp_commands::create_md_api,
            ctp_commands::release_md_api,
            ctp_commands::create_trader_api,
            ctp_commands::release_trader_api,
            ctp_commands::md_login,
            ctp_commands::trader_login,
            ctp_commands::subscribe_market_data,
            ctp_commands::unsubscribe_market_data,
            ctp_commands::insert_order,
            ctp_commands::cancel_order,
            ctp_commands::get_cancel_order_result,
            ctp_commands::query_account,
            ctp_commands::query_position,
            ctp_commands::query_instruments,
            ctp_commands::validate_trader_session,
            ctp_commands::get_active_trader_session,
            ctp_commands::test_order_interface,
            ctp_commands::check_ctp_connection_status,
            ctp_commands::force_set_trader_login_status,
            ctp_commands::get_session_info,
            ctp_commands::query_all_orders,
            ctp_commands::query_order_remaining_volume,
            ctp_commands::query_all_remaining_volumes,
            ctp_commands::check_settlement_confirm_status,
            ctp_commands::settlement_info_confirm,
            ctp_commands::diagnose_order_fields,
            ctp_commands::check_order_insert_result,
            ctp_commands::analyze_order_rejection,
            ctp_commands::check_order_submission_status,
            ctp_commands::cleanup_current_dir_cache_command,
            ctp_commands::validate_order_request,
            audio_commands::play_error_sound,
            audio_commands::play_audio_file,
            audio_commands::set_audio_volume,
            audio_commands::get_available_audio_files,
        ])
        .setup(|app| {
            // 设置全局App Handle用于发送事件
            ctp_commands::set_app_handle(app.handle().clone());
            
            // 记录Tauri应用设置完成
            logger::log_tauri_event("setup", "Application setup completed");
            
            Ok(())
        })
        .on_window_event(|window, event| {
            // 记录窗口事件
            match event {
                tauri::WindowEvent::CloseRequested { .. } => {
                    logger::log_window_event(window.label(), "close_requested", "User requested window close");
                }
                tauri::WindowEvent::Destroyed => {
                    logger::log_window_event(window.label(), "destroyed", "Window destroyed");
                }
                // tauri::WindowEvent::Focused(focused) => {
                //     logger::log_window_event(window.label(), "focused", &format!("focused={}", focused));
                // }
                // tauri::WindowEvent::Resized(size) => {
                //     logger::log_window_event(window.label(), "resized", &format!("size={}x{}", size.width, size.height));
                // }
                _ => {} // 忽略其他事件以避免日志过多
            }
        })
        .run(tauri::generate_context!())
        .unwrap_or_else(|err| {
            logger::log_fatal_error(&format!("Tauri application failed to run: {}", err), "main");
            eprintln!("error while running tauri application: {}", err);
        });
    
    // 记录应用正常关闭
    logger::log_app_shutdown("normal");
}

/// 设置全局panic处理器
fn setup_panic_handler() {
    std::panic::set_hook(Box::new(|panic_info| {
        let location = panic_info.location().map(|loc| {
            format!("{}:{}:{}", loc.file(), loc.line(), loc.column())
        });
        
        let panic_message = if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
            s.to_string()
        } else if let Some(s) = panic_info.payload().downcast_ref::<String>() {
            s.clone()
        } else {
            "Unknown panic occurred".to_string()
        };
        
        // 记录panic到日志（如果日志系统已初始化）
        logger::log_panic(&panic_message, location.as_deref());
        
        // 同时输出到stderr
        eprintln!("PANIC: {} at {}", panic_message, location.unwrap_or("unknown location".to_string()));
        
        // 记录内存使用情况
        logger::log_memory_usage();
    }));
}

/// 设置优雅关闭处理器
fn setup_shutdown_handler() {
    // 设置Ctrl+C处理器
    tokio::spawn(async {
        tokio::signal::ctrl_c().await.ok();
        logger::log_app_shutdown("ctrl_c_signal");
        std::process::exit(0);
    });
}
